package com.tastyshop.controller;

import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.tastyshop.domain.NoticeBoard;
import com.tastyshop.service.NoticeBoardService;

@Controller
public class NoticeBoardController {

	@Autowired
	private NoticeBoardService service;

	@RequestMapping(value = "notice.do", method = RequestMethod.GET)
	public String notice(HttpServletRequest request, Model model) {
		int page = 1;
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}
		int rows = 10;

		String field = "";
		if (request.getParameter("field") != null) {
			field = request.getParameter("field");
		}

		String keyword = "";
		if (request.getParameter("keyword") != null) {
			keyword = request.getParameter("keyword");
		}

		if ("".equals(keyword)) {
			field = "";
		}

		List<NoticeBoard> noticeBoards = service.getNoticeList(field, keyword,
				page, rows);

		int cnt = noticeBoards.size();
		String totCnt = "";
		totCnt = noticeBoards.get(0).getTOT_CNT();
		int viewCnt = 10;
		int totalCnt = Integer.parseInt(totCnt);
		int pageCnt = totalCnt / viewCnt + (totalCnt % viewCnt == 0 ? 0 : 1);
		int startPage = 1;
		if (page % 10 != 0) {
			startPage = (int) (page / 10) * 10 + 1;
		} else {
			startPage = ((int) (page / 10) - 1) * 10 + 1;
		}
		int totalPage = (int) Math.ceil((totalCnt / (double) viewCnt));
		int pageBlock = 10;
		int endPage = startPage + pageBlock - 1;
		if (endPage > pageCnt)
			endPage = pageCnt;
		
		model.addAttribute("totalPage", totalPage);
		model.addAttribute("cnt", cnt);
		model.addAttribute("noticeBoards", noticeBoards);
		model.addAttribute("totCnt", totCnt);
		model.addAttribute("keyword", keyword);
		model.addAttribute("field", field);
		model.addAttribute("page", page);
		model.addAttribute("startPage", startPage);
		model.addAttribute("endPage", endPage);
		return "notice";
	}

	@RequestMapping(value = "notice_detail.do")
	public String detail(@RequestParam("idx") int idx, Model model){
		HashMap<String, NoticeBoard> map = service.getInfo(idx);
		NoticeBoard noticeBoard = map.get("noticeBoard");
		noticeBoard.setContent(noticeBoard.getContent().replaceAll("\n", "<br />"));
		model.addAttribute("noticeBoard", noticeBoard);
		model.addAttribute("prev", map.get("prev"));
		model.addAttribute("next", map.get("next"));
		service.hitCount(idx);
		return "notice_detail";
	}

}
